package fr.kotton.myorganizer.task.fragment;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.LinkedList;

import fr.kotton.myorganizer.MainActivity;
import fr.kotton.myorganizer.R;
import fr.kotton.myorganizer.bean.Task;
import fr.kotton.myorganizer.bean.TaskGroup;
import fr.kotton.myorganizer.db.MyOrganizerDbContract.TaskEntry;
import fr.kotton.myorganizer.db.MyOrganizerDbContract.TaskGroupEntry;
import fr.kotton.myorganizer.db.MyOrganizerDbContract.TaskToTaskGroupEntry;
import fr.kotton.myorganizer.db.MyOrganizerDbHelper;
import fr.kotton.myorganizer.task.activity.ViewTaskActivity;
import fr.kotton.myorganizer.task.adapter.TasksListAdapter;
import fr.kotton.myorganizer.task.interfaces.TaskGroupsQueryCompleteListener;
import fr.kotton.myorganizer.task.interfaces.TasksQueryCompleteListener;
import fr.kotton.myorganizer.utils.Consts;
import fr.kotton.myorganizer.utils.sql.DatabaseReader;
import fr.kotton.myorganizer.utils.sql.DbToBeanConverter;
import fr.kotton.myorganizer.utils.sql.SqlRawQuery;
import fr.kotton.myorganizer.utils.sql.SqlReadQuery;

public class ListTasksFragment extends Fragment implements TasksQueryCompleteListener {

    String[] title = new String[]{"Tâche 1", "Tâche 2", "Tâche 3", "Tâche 4"};
    String[] date = new String[]{"2007-03-12T00:30:00+0100", "2007-03-13T01:30:00+0100", "2007-03-14T00:30:00+0100", "2007-03-15T01:30:00+0100"};
    String[] groupe = new String[]{"1", "2", "3", null};
    // String[] groupe_couleur = new String[]{"#9b59b6", "#2ecc71", "#34495e"};

    TasksQueryCompleteListener mTasksDbQueryCompletedListener;
    TaskGroupsQueryCompleteListener mTaskGroupsDbQueryCompletedListener;
    private TasksListAdapter mListViewAdapter;
    private MyOrganizerDbHelper mDbHelper;
    private Activity mActivity;
    private DatabaseReader mDatabaseReader;

    @Override
    public void onAttach(Activity pActivity) {
        super.onAttach(pActivity);
        ((MainActivity) pActivity).onSectionAttached(getArguments().getInt(Consts.FRAGMENT_REF_STRING));
        mActivity = pActivity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        setHasOptionsMenu(true);

        View rootView = inflater.inflate(R.layout.fragment_tasks, container, false);

        // Permet l'accès à la base de données
        mDbHelper = new MyOrganizerDbHelper(mActivity);

        // Configuration du layout de la listview
        ListView lListView = (ListView) rootView.findViewById(R.id.listview);

        // Configuration des callbacks appelés lorsqu'une requête DB est terminée
        mTasksDbQueryCompletedListener = new TasksQueryCompleteListener() {

            @Override
            public void onTasksReadQueryComplete(Cursor pCursor) {
                parseTasksReadQueryResult(pCursor);
                mListViewAdapter.clearUnusedHeaders();
            }

            @Override
            public void onTasksDeleteQueryComplete() {
                updateTasksListview();
            }
        };

        mTaskGroupsDbQueryCompletedListener = new TaskGroupsQueryCompleteListener() {
            @Override
            public void onTaskGroupsReadQueryComplete(Cursor pCursor) {
                parseTaskGroupsReadQueryResult(pCursor);
            }

            @Override
            public void onTaskGroupsDeleteQueryComplete() {

            }
        };

        // Configuration de l'adapter pour la listview
        mListViewAdapter = new TasksListAdapter(mActivity, android.R.layout.simple_list_item_1, mTasksDbQueryCompletedListener);
        lListView.setAdapter(mListViewAdapter);

        lListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int pPosition, long id) {
                Intent lIntent = new Intent(mActivity, ViewTaskActivity.class);
                lIntent.putExtra(Consts.INTENT_REF_TASK_ID, mListViewAdapter.getItem(pPosition).getId());
                startActivity(lIntent);
            }
        });

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        requestTaskGroupsList();
        requestTasksList();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.fragment_tasks_action_bar, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == R.id.action_add_task) {
            addTask();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void parseTasksReadQueryResult(Cursor pCursor) {
        if (pCursor != null) {
            LinkedList<Task> lTasksList = DbToBeanConverter.DbToTasks(pCursor);

            mListViewAdapter.addMultipleTasks(lTasksList);
        }
    }

    public void updateTasksListview() {
        mListViewAdapter.notifyDataSetChanged();
    }

    public void parseTaskGroupsReadQueryResult(Cursor pCursor) {
        if (pCursor != null) {
            LinkedList<TaskGroup> lTaskGroupsList = DbToBeanConverter.DbToTaskGroups(pCursor);

            mListViewAdapter.addMultipleTaskGroups(lTaskGroupsList);
        }
    }

    public void addTask() {

        // Gets the data repository in write mode
        SQLiteDatabase db = mDbHelper.getWritableDatabase();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

        for (int i = 0; i < title.length; i++) {

            // Create a new map of values, where column names are the keys
            ContentValues lTaskValues = new ContentValues();
            lTaskValues.put(TaskEntry.COLUMN_NAME_TASK_TITLE, title[i]);

            try {
                long dateInMs = dateFormat.parse(date[i]).getTime();
                lTaskValues.put(TaskEntry.COLUMN_NAME_TASK_ENDDATE, dateInMs);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            // Insert the new row, returning the primary key value of the new row
            long lJustCreatedId = db.insert(
                    TaskEntry.TABLE_NAME,
                    TaskEntry.COLUMN_NAME_TASK_NULLABLE,
                    lTaskValues);

            if (groupe[i] != null) {

                ContentValues lTaskGroupValues = new ContentValues();
                lTaskGroupValues.put(TaskToTaskGroupEntry.COLUMN_NAME_TASKTOTASKGROUP_TASK_ID, lJustCreatedId);
                lTaskGroupValues.put(TaskToTaskGroupEntry.COLUMN_NAME_TASKTOTASKGROUP_TASKGROUP_ID, groupe[i]);

                // Insert the new row, returning the primary key value of the new row
                db.insert(
                        TaskToTaskGroupEntry.TABLE_NAME,
                        TaskToTaskGroupEntry.COLUMN_NAME_TASKTOTASKGROUP_NULLABLE,
                        lTaskGroupValues);
            }
        }
    }

    @Override
    public void onTasksReadQueryComplete(Cursor pCursor) {
        parseTasksReadQueryResult(pCursor);
    }

    @Override
    public void onTasksDeleteQueryComplete() {
        updateTasksListview();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mDatabaseReader != null) {
            mDatabaseReader.cancel(true);
        }
    }

    private void requestTaskGroupsList() {

        // Requête pour récupérer la liste des groupes

        // Choix des colonnes à inclure dans le select sur la DB
        String[] lColumns = {
                TaskGroupEntry.COLUMN_NAME_TASKGROUP_ID,
                TaskGroupEntry.COLUMN_NAME_TASKGROUP_NAME,
                TaskGroupEntry.COLUMN_NAME_TASKGROUP_COLOR
        };

        // Choix du tri des résultats obtenu
        String lSortOrder = TaskGroupEntry.COLUMN_NAME_TASKGROUP_NAME + " ASC";

        // Création de la requête qui va remonter la liste des tâches à afficher
        SqlReadQuery lSqlReadQuery = new SqlReadQuery();
        lSqlReadQuery.setTable(TaskGroupEntry.TABLE_NAME);
        lSqlReadQuery.setColumns(lColumns);
        lSqlReadQuery.setOrderBy(lSortOrder);

        // Exécution de la requête
        mDatabaseReader = new DatabaseReader(getActivity(), mTaskGroupsDbQueryCompletedListener);
        mDatabaseReader.execute(lSqlReadQuery);
    }

    private void requestTasksList() {
        // Requête pour récupérer la liste des tâches
        SqlRawQuery lSqlRawQuery = new SqlRawQuery();
        lSqlRawQuery.setQuery("SELECT task.task_id, Title, endDate, task_to_task_group.task_id as task_id_ref, task_to_task_group.taskgroup_id, task_group.name, task_group.color FROM task LEFT JOIN task_to_task_group ON task_id_ref = task.task_id LEFT JOIN task_group ON task_to_task_group.taskgroup_id = task_group.taskgroup_id ORDER BY endDate ASC");
        mDatabaseReader = new DatabaseReader(getActivity(), mTasksDbQueryCompletedListener);
        mDatabaseReader.execute(lSqlRawQuery);
    }
}
